package com.example.demo.base.config.auth;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.example.demo.base.login.dto.UserCache;
import com.example.demo.constants.BusinessExceptionCode;
import com.example.demo.exception.BusinessException;

import java.util.Optional;

public class UserInfoShareHolder {

    private static final ThreadLocal<UserCache> USER_INFO_THREAD_LOCAL = new TransmittableThreadLocal<>();

    /**
     * 存储用户信息
     */
    public static void setUserInfo(UserCache userInfo) {
        USER_INFO_THREAD_LOCAL.set(userInfo);
    }

    /**
     * 获取用户相关信息
     */
    public static UserCache getUserInfo() {
        Optional<UserCache> userCache = Optional.ofNullable(USER_INFO_THREAD_LOCAL.get());
        if (userCache.isPresent()){
            return userCache.get();
        }else {
            return new UserCache();
        }
    }

    /**
     * 清除ThreadLocal信息
     */
    public static void remove() {
        USER_INFO_THREAD_LOCAL.remove();
    }
}
